package com.tanger.im.service.user;

import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import com.tanger.im.entity.ImUser;
import com.tanger.im.entity.ImUserAddress;
import com.tanger.im.entity.IMUserVO;
import com.tanger.im.mapper.IMUserRepository;
import com.tanger.im.service.address.IMUserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Description TODO
 * @Author Hchenbin
 * @Date 2023-12-25 15:43
 * @Version 1.0
 */
@Slf4j
@Service
public class IMUserServiceImpl implements IMUserService {

    @Autowired
    private IMUserRepository repository;
    @Autowired
    private IMUserAddressService addressService;

    @Override
    public IMUserVO findOneById(Long id) {
        return repository.findById(id)
                .map(this::toMap)
                .orElse(null);
    }

    @Override
    public IMUserVO findOne(Long userId) {
        // TODO 待处理逻辑:获取IM用户为空时自动注册系统用户为IM用户
        return repository.findOne(Example.of(new ImUser(userId,1,0)))
                .map(this::toMap)
                .orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult save(IMUserVO vo) {
        ImUser user = repository.findOne(Example.of(new ImUser(vo.getUserId(),1,0))).orElse(null);
        if (Objects.isNull(user)) {
            user = BeanUtils.copyProperties(vo, new ImUser());
            user.setIsDel(0);
            user.setStatus(1);
            user.setCreateTime(System.currentTimeMillis());
            repository.save(user);

            ImUserAddress address = vo.getAddress();
            if (Objects.nonNull(address)) {
                address.setUserId(user.getId());
                addressService.save(vo.getAddress());
            }
            return ActionResult.buildResultSuccess("OK");
        }

        BeanUtils.copyProperties(vo, user);
        repository.saveAndFlush(user);

        ImUserAddress address = vo.getAddress();
        if (Objects.nonNull(address)) {
            address.setUserId(user.getId());
            addressService.save(vo.getAddress());
        }
        return ActionResult.buildResultSuccess("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult cancel(Long id) {
        ImUser user = repository.findById(id)
                .orElseThrow(() -> new RuntimeException("当前用户信息不存在"));
        user.setIsDel(1);
        repository.saveAndFlush(user);
        return ActionResult.buildResultSuccess("OK");
    }

    public IMUserVO toMap(ImUser user) {
        IMUserVO vo = BeanUtils.copyProperties(user, new IMUserVO());
        vo.setAddress(addressService.findOneByUserId(vo.getId()));
        return vo;
    }
}
